package com.legendshop.oa.security;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;

import com.legendshop.oa.constants.Constants;

public class MyLoginUrlAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint {
	

	//HttpSessionRequestCache
	static final String SAVED_REQUEST = "SPRING_SECURITY_SAVED_REQUEST";
	
	public MyLoginUrlAuthenticationEntryPoint(String loginFormUrl) {
		super(loginFormUrl);
	}


   /**
    * 计算返回的URL
    *
    * @param request   the request
    * @param response  the response
    * @param exception the exception
    * @return the URL (cannot be null or empty; defaults to {@link #getLoginFormUrl()})
    */
   @Override
   protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response,
           AuthenticationException exception) {
   	DefaultSavedRequest savedRequest =  (DefaultSavedRequest)request.getSession().getAttribute(SAVED_REQUEST);
   	if(savedRequest != null){
   		return appendUrl(getLoginFormUrl() ,savedRequest.getRedirectUrl()); 
   	}else{
   		return getLoginFormUrl();
   	}
   }
    
    
    private String appendUrl(String url, String returnUrl){
    	String newUrl = url;
    	if(url.endsWith("/")){
    		newUrl = url.substring(0, url.length() -1);
    	}
    	String returnUrl1 = null;
		try {
			returnUrl1 = URLEncoder.encode(returnUrl, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
    	if(newUrl.indexOf("?")>0){
    		return newUrl + "&" + Constants.RETURN_URL + "=" + returnUrl1;
    	}else{
    		return newUrl + "?" + Constants.RETURN_URL + "=" + returnUrl1;
    	}
    }

}
